import { Component, OnInit, ViewChild } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;

@Component({
    selector: 'sa-record-second',
    templateUrl: './record-second.component.html',
    styleUrls: ['./record-second.css']
})
export class RecordSecondComponent implements OnInit {
    isShow = false
    tableData = []
    pageOffset = 0
    totalCount = 1
    curPage = 1
    pageSize = 10
    tableParam = {
        carNumber: '',
        startTime: '',
        endTime: '',
        companyId: '',
        examineStatus: '',
        isCorrect: '',
        dateType: '2',
        level: '2',
        examineUser: ''
    }
    tableColumn = []
    checkingColumn = [
        {
            label: '操作',
            type: 'button'
        }, {
            label: '初审状态',
            key: 'isCorrect',
            fun: this.firstCorrectFilter
        }, {
            label: '设备ID',
            key: 'deviceId'
        }, {
            label: '车牌号码',
            key: 'carNumber'
        }, {
            label: '父级公司',
            key: 'parentCompanyName'
        }, {
            label: '所属公司',
            key: 'companyName'
        }, {
            label: '省份',
            key: 'province'
        }, {
            label: '用途分类',
            key: 'useClassify',
            fun: this.getCarInforFilter
        }, {
            label: '硬件版本',
            key: 'hwVersion'
        }, {
            label: '传感器类型',
            key: 'sensorType',
            type: 'html'
        }, {
            label: '完成安装时间',
            key: 'installDate'
        }, {
            label: '审核时间',
            key: 'examineDate'
        }, {
            label: '创建时间',
            key: 'createTime'
        }, {
            label: '录入人员',
            key: 'installUser'
        }
    ]
    checkedColumn = [
        {
            label: '操作',
            type: 'button'
        }, {
            label: '审核状态',
            key: 'examineStatus',
            fun: this.examineStatusFilter
        }, {
            label: '审核人员',
            key: 'examineUserName'
        }, {
            label: '设备ID',
            key: 'deviceId'
        }, {
            label: '车牌号码',
            key: 'carNumber'
        }, {
            label: '父级公司',
            key: 'parentCompanyName'
        }, {
            label: '所属公司',
            key: 'companyName'
        }, {
            label: '省份',
            key: 'province'
        }, {
            label: '用途分类',
            key: 'useClassify',
            fun: this.getCarInforFilter
        }, {
            label: '硬件版本',
            key: 'hwVersion'
        }, {
            label: '传感器类型',
            key: 'sensorType',
            type: 'html'
        }, {
            label: '完成安装时间',
            key: 'installDate'
        }, {
            label: '录入人员',
            key: 'installUser'
        }, {
            label: '最近提交人',
            key: 'latelyExamineUserName'
        }, {
            label: '审核时间',
            key: 'examineDate'
        }, {
            label: '创建时间',
            key: 'createTime'
        }
    ]
    checkFirstColumn = [
        {
            label: '操作',
            type: 'button'
        }, {
            label: '设备ID',
            key: 'deviceId'
        }, {
            label: '审核状态',
            key: 'examineStatus',
            fun: this.examineStatusFilter,
            isShow: true
        }, {
            label: '初审是否正确',
            key: 'isCorrect',
            fun: this.isCorrectFilter,
            isShow: true
        }, {
            label: '车牌号码',
            key: 'carNumber'
        }, {
            label: '父级公司',
            key: 'parentCompanyName'
        }, {
            label: '所属公司',
            key: 'companyName'
        }, {
            label: '省份',
            key: 'province'
        }, {
            label: '用途分类',
            fun: this.getCarInforFilter
        }, {
            label: '硬件版本',
            key: 'hwVersion'
        }, {
            label: '传感器类型',
            key: 'sensorType',
            type: 'html'
        }, {
            label: '完成安装时间',
            key: 'installDate'
        }, {
            label: '审核时间',
            key: 'examineDate'
        }, {
            label: '创建时间',
            key: 'createTime'
        }, {
            label: '录入人员',
            key: 'installUser'
        }, {
            label: '审核人员',
            key: 'examineUserName'
        }, {
            label: '最近提交人',
            key: 'latelyExamineUserName',
            isShow: true
        }
    ]
    deviceInstallExamine = {
        examineInfoList: [],
        imageInfo: [],
        firstExamineResultInfo: {}
    }
    car = {
        sensorChannel: []
    }
    sensorType = []
    constructor(private jsonApiService: JsonApiService,) {
    }

    ngOnInit() {
        this.tableColumn = this.checkingColumn
        System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
            System.import('assets/js/select2-zh-CN.js').then(() => {
                this.select2Car(); //初始化select 2 车辆
                this.selectCheckPerson()
            });
        })
        this.initDate().then(() => this.load());
        this.getSensorType()
    }

    firstCorrectFilter(row) {
        let strArr = []
        for (const key in row.firstExamineResult) {
            if (row.firstExamineResult.hasOwnProperty(key)) {
                strArr.push(`${key}: ${row.firstExamineResult[key]}`)
            }
        }
        return strArr.join(';')
    }

    examineStatusFilter(row) {
        return ['待审核', '审核通过', '审核不通过'][row.examineStatus]
    }

    isCorrectFilter(row) {
        return ['初审中', '复审中', '正确', '错误'][row.isCorrect]
    }

    getSensorType() {
        this.jsonApiService.http('sensorManage/querySensorList.html', '').subscribe((data) => {
            if (data.success) {
                this.sensorType = data.data
            }
        })
    }

    getCarInforFilter(row) {
        return carTypeListObj.carDeatailUseList[row.useClassify]
    }

    companySelected(data) {
        this.tableParam.companyId = data.companyId;
    }

    selectCheckPerson() {
        var that = this
        $('#checkPerson').select2({
            language: "zh-CN",
            placeholder: "请选择",
            allowClear: true,
            minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
            ajax: {
                url: config.BaseURL + "deviceInstallAuditor/queryAllUser.html",
                dataType: 'json',
                delay: 50,
                method: "GET",
                xhrFields: {
                    withCredentials: true
                },
                data: function (params) {
                    return {
                        "key": params.term // search term
                    };
                },
                processResults: function (data, params) {
                    const options = []
                    data.data.forEach(item => {
                        options.push({
                            id: item.userId,
                            text: item.userName
                        })
                    })
                    return {
                        results: options //获取查询后的结果
                    };
                },
                cache: true
            }
        }).on("select2:select", function (e) {
            that.tableParam.examineUser = e.params.data.id
        });
    }

    select2Car() {
        var that = this;
        $("#carNumberSelect2Second").select2({
            language: "zh-CN",
            placeholder: "请选择",
            allowClear: true,
            minimumInputLength: 2, //最少2个字符，select2才显示查询的内容

            ajax: {
                url: config.BaseURL + "stats/carListByCarNumber.html",
                dataType: 'json',
                delay: 50,
                method: "POST",
                xhrFields: {
                    withCredentials: true
                },
                data: function (params) {
                    return {
                        "carNumber": params.term // search term
                    };
                },
                processResults: function (data, params) {
                    var options = new Array();
                    // 小于10个数量才判断重复
                    if (data.data.length <= 10) {
                        let arr = []
                        let sameCar = []
                        // 判断相同的车牌号
                        for (let index = 0; index < data.data.length; index++) {
                            let car = data.data[index];
                            if (arr.indexOf(car.carNumber) != -1) {
                                sameCar.push(car.carNumber)
                            } else {
                                arr.push(car.carNumber);
                            }
                        }
                        $(data.data).each(function (index, car) {
                            if (sameCar.indexOf(car.carNumber) != -1) {
                                options.push({
                                    id: car.deviceId,
                                    text: car.carNumber + "[" + car.parentName + "]"
                                })
                            } else {
                                options.push({
                                    id: car.deviceId,
                                    text: car.carNumber
                                })
                            }
                        });
                    } else {
                        $(data.data).each(function (index, car) {
                            options.push({
                                id: car.deviceId,
                                text: car.carNumber
                            })
                        });
                    }
                    return {
                        results: options //获取查询后的结果
                    };
                },
                cache: true
            },
            templateResult: this.formatRepo
        }).on("select2:select", function (e) {
            var data = e.params.data;
            if (data.text.indexOf('[') > 0) {
                that.tableParam.carNumber = data.text.split('[')[0];
            } else {
                that.tableParam.carNumber = data.text;
            }
        });
    }

    //select2 格式回调函数
    formatRepo(state) {
        if (!state.id) { return state.text };
        var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
        return $state;
    }

    delCarNumber() {
        this.tableParam.carNumber = '';
        var str = $("<span class='select2-selection__placeholder'>请选择</span>");
        $('#carNumberSelect2Second').val("").change();
        $("#select2-carNumberSelect2-container").empty();
        $("#select2-carNumberSelect2-container").attr("title", "");
        $("#select2-carNumberSelect2-container").prepend(str);
    }

    delPerson() {
        this.tableParam.examineUser = ''
        $('#checkPerson').val("").change();
    }

    delDate() {
        this.tableParam.startTime = '';
        this.tableParam.endTime = '';
        $("#datetimepicker1").val('').change();
        $("#datetimepicker2").val('').change();
        $("#datetimepicker2").datetimepicker("setStartDate", null);
        $("#datetimepicker1").datetimepicker("setEndDate", null);
    }

    initDate() {
        var that = this;
        return new Promise(function (resolve, reject) {
            System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
                System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
                    $("#datetimepicker1").datetimepicker({//时间插件
                        format: "yyyy-mm-dd hh:ii:ss",
                        language: "zh-CN",
                        autoclose: true,
                    }).on("changeDate", function (e) {
                        var date = e.date;
                        var time = common.getTimeMmss(date);
                        $("#datetimepicker2").datetimepicker("setStartDate", time);
                        that.tableParam.startTime = time;
                    });
                    $("#datetimepicker2").datetimepicker({//时间插件
                        format: "yyyy-mm-dd hh:ii:ss",
                        language: "zh-CN",
                        autoclose: true,
                    }).on("changeDate", function (e) {
                        var date = e.date;
                        var time = common.getTimeMmss(date);
                        $("#datetimepicker1").datetimepicker("setEndDate", time);
                        that.tableParam.endTime = time;
                    });
                    var date = new Date();
                    $("#datetimepicker2").val(that.getTime(date));//当前时间
                    that.tableParam.endTime = that.getTime(date)
                    date.setDate(date.getDate() - 7);//设置前一天
                    $("#datetimepicker1").val(that.getTime(date));
                    that.tableParam.startTime = that.getTime(date)
                    resolve();
                });
            }
            );
        })
    }

    getTime(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    }

    tableSearch() {
        this.load()
    }

    exportData() {
        const param = {
            ...this.tableParam,
            user: this.tableParam.examineUser
        }
        delete param.examineUser
        common.exprotDataFile(param, 'param', config.BaseURL + 'deviceInstallExamine/exportDeviceInstallExamineLevel2Data.html')
    }

    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }

    load() {
        const param = {
            nowPage: this.curPage,
            pageSize: this.pageSize,
            parameters: { ...this.tableParam }
        }

        this.jsonApiService.json_http("deviceInstallExamine/queryDeviceInstallExamineListLevel2.html", param).subscribe(data => {
            this.tableData = data.exhibitDatas;
            this.totalCount = data.recordCount;
        })
    }

    switchTab(index) {
        if (this.tableParam.level === '2') {
            if (index === '0' || index === '') {
                this.tableColumn = this.checkingColumn
            } else {
                this.tableColumn = this.checkedColumn
            }
        }
        this.tableParam.examineStatus = index.toString()
        this.curPage = 1
        this.load()
    }

    switchTabTop(index) {
        this.tableParam.level = index
        if (this.tableParam.level === '2') {
            if (this.tableParam.examineStatus === '0' || this.tableParam.examineStatus === '') {
                this.tableColumn = this.checkingColumn
            } else {
                this.tableColumn = this.checkedColumn
            }
            this.tableParam.examineUser = ''
        } else {
            this.tableColumn = this.checkFirstColumn
        }
        this.load()
    }

    getDetail(row, dom) {
        this.jsonApiService.http('deviceInstallExamine/deviceInstallExamine.html?id=' + row.id, {}).subscribe(res => {
            this.deviceInstallExamine = res.data.deviceInstallExamine
            this.car = res.data.car
            this.isShow = true
            dom.show()
        })
    }

    imgClose(val) {
        val.hide();
        this.isShow = false
    }

    cancelCheck(dom) {
        dom.hide()
        this.isShow = false
    }

    handleWindowHidden() {
        this.isShow = false
    }

    @ViewChild('recordModal') recordModal
    submit() {
        this.recordModal.submit()
    }

    submitSuccess(dom) {
        dom.hide()
        this.load()
    }
}